let proxies = [
  {ip: '218.92.143.27', port: '18027', username: 'pc326', pwd: '111'},
  {ip: '218.92.143.32', port: '18032', username: 'pc326', pwd: '111'},
  {ip: '58.220.21.162', port: '16162', username: 'pc326', pwd: '111'},
  {ip: '58.220.21.177', port: '16177', username: 'pc326', pwd: '111'},
  {ip: '180.97.187.202', port: '26202', username: 'pc326', pwd: '111'},
  {ip: '180.97.187.207', port: '26207', username: 'pc326', pwd: '111'},
  {ip: '43.242.157.132', port: '18132', username: 'pc326', pwd: '111'},
  {ip: '43.242.157.137', port: '18137', username: 'pc326', pwd: '111'},
  {ip: '220.167.106.177', port: '18177', username: 'pc326', pwd: '111'},
  {ip: '220.167.106.207', port: '18207', username: 'pc326', pwd: '111'},

];

document.addEventListener('DOMContentLoaded', function () {
  chrome.runtime.sendMessage({message: "status"}, function(response) {
    console.log(response)
    if (response.status === 'started') {
      document.getElementById('link').style.display = 'none'
      document.getElementById('crawl-start').style.display = 'none'
      document.getElementById('crawl-stop').style.display = 'block'
      document.getElementById('current-count-layout').style.display = 'block'
      document.getElementById('current-count').innerText = response.count
    } else if (response.status === 'stoped') {
      document.getElementById('link').style.display = 'block'
      document.getElementById('crawl-start').style.display = 'block'
      document.getElementById('crawl-stop').style.display = 'none'
      document.getElementById('current-count-layout').style.display = 'none'
    } else if (response.status === 'finished') {
      document.getElementById('link').style.display = 'block'
      document.getElementById('crawl-start').style.display = 'block'
      document.getElementById('crawl-stop').style.display = 'none'
      document.getElementById('current-count-layout').style.display = 'block'
    }
    updateProxyList(response.proxies)
  });
  document.getElementById('crawl-start').addEventListener('click', function () {
    chrome.runtime.sendMessage({"message": "crawl-start"});
    window.close()
  })
  document.getElementById('crawl-stop').addEventListener('click', function () {
    chrome.runtime.sendMessage({"message": "crawl-stop"});
    window.close()
  })
  document.getElementById('link').addEventListener('click', function () {
    chrome.tabs.create({url: 'http://deal.ggzy.gov.cn/ds/deal/dealList.jsp'});
    return false;
  })
  document.getElementById('crawl-details').addEventListener('click', function () {
    chrome.runtime.sendMessage({"message": "crawl-details"});
    window.close()
  })
  document.getElementById('crawl-new-0').addEventListener('click', function () {
    let usage = {"category":"工程建设","city":"0","classify":"01","currentIndex":0,"currentPage":"0","dealTime":"06","endDate":"2018-07-16","platform":"0","province":"0","stage":"0100","startDate":"2018-07-15","trade":"0"}
    let result = prompt('创建[工程建设]抓取记录：', JSON.stringify({"startDate":"2018-07-15","endDate":"2018-07-16","currentPage":"1"}))
    let timeRange = JSON.parse(result)
    usage["startDate"] = timeRange["startDate"]
    usage["endDate"] = timeRange["endDate"]
    usage["currentPage"] = timeRange["currentPage"]
    chrome.storage.local.get(['usage'], function(result) {
      let history = result.usage
      history[usage['category'] + ':' + usage.startDate + '-' + usage.endDate] = usage
      chrome.storage.local.set({usage: history});
      window.close()
    })
  })
  document.getElementById('crawl-new-1').addEventListener('click', function () {
    let usage = {"category":"政府采购","city":"0","classify":"02","currentIndex":0,"currentPage":"0","dealTime":"06","endDate":"2018-07-20","platform":"0","province":"0","stage":"0200","startDate":"2018-07-15","trade":"0"}
    let result = prompt('创建[政府采购]抓取记录：', JSON.stringify({"startDate":"2018-07-15","endDate":"2018-07-16","currentPage":"1"}))
    let timeRange = JSON.parse(result)
    usage["startDate"] = timeRange["startDate"]
    usage["endDate"] = timeRange["endDate"]
    usage["currentPage"] = timeRange["currentPage"]
    chrome.storage.local.get(['usage'], function(result) {
      let history = result.usage
      history[usage['category'] + ':' + usage.startDate + '-' + usage.endDate] = usage
      chrome.storage.local.set({usage: history});
      window.close()
    })
  })

  chrome.storage.local.get(['usage'], function(result) {
    let history = result.usage
    for (let key in history) {
      let usage = history[key]
      let item_div = document.createElement('div')
      item_div.style.whiteSpace = 'nowrap'
      let ele = document.createElement('a')
      ele.style = 'margin-top: 12px; margin-bottom: 12px;'
      if (!usage.finished) {
        ele.innerText = key + '|' + usage.currentPage + '/' + (usage.pageCount || '')
        ele.setAttribute('href', 'javascript;')
        ele.addEventListener('click', function () {
          chrome.runtime.sendMessage({"message": "crawl-start", startPosition: usage});
          window.close()
        })
        ele.title = '继续抓取'
      } else {
        ele.innerText = '[已完成] ' + key + '|' + usage.currentPage + '/' + (usage.pageCount || '')
      }
      item_div.appendChild(ele)
      let remove = document.createElement('a')
      remove.style.padding = '5px'
      remove.style.cursor = 'pointer'
      remove.innerText = '删除'
      remove.addEventListener('click', function () {
        let result = confirm('删除：' + key)
        if (result) {
          delete history[key]
          document.getElementById('crawl-record').removeChild(item_div)
          chrome.storage.local.set({usage: history});
          chrome.runtime.sendMessage({
            "message": "remove-crawl-history",
            key: key
          })
        }
      })
      item_div.appendChild(remove)
      let edit  = document.createElement('a')
      edit.style.padding = '5px'
      edit.style.cursor = 'pointer'
      edit.innerText = '修改'
      edit.addEventListener('click', function () {
        let result = prompt('修改记录：' + key, JSON.stringify(usage))
        if (result) {
          usage = JSON.parse(result)
          history[usage.startDate + '-' + usage.endDate] = usage
          chrome.storage.local.set({usage: history});
          window.close()
        }
      })
      item_div.appendChild(edit)
      item_div.appendChild(remove)
      document.getElementById('crawl-record').appendChild(item_div)
    }
  });
  updateProxyList()
})

function updateProxyList(enabledProxies) {
  document.getElementById('proxy-list').innerHTML = ''
  if (!proxies) return
  proxies.forEach(function (proxy, index) {
    let item_div = document.createElement('div')
    let ele = document.createElement('span')
    ele.innerText = index + 1 + '. ' + proxy.ip + ":" + proxy.port
    let check = document.createElement('input')
    check.type='checkbox'
    check.style.padding = '5px'
    check.addEventListener('click', function () {
      chrome.runtime.sendMessage({"message": "set-proxy", extra: {
        proxy: proxy,
        add: check.checked
      }});
    })
    if (enabledProxies) {
      enabledProxies.forEach(function (p) {
        if (p.ip === proxy.ip) {
          check.checked = true
        }
      })
    }
    item_div.appendChild(check)
    item_div.appendChild(ele)
    document.getElementById('proxy-list').appendChild(item_div)
  })
}
